package com.example.gokuplayalong.bases.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.*;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.example.gokuplayalong.bases.base.AppParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class DirectPay {

    static String APPID = "2021005116652932";
    static String PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCGkTrzyT7zTCbqtsmywesLnD5gp1mVdWIUy0vraXQBOkvXZVvuxeiUXq4Pl1WREUx10EneoHnLIilrFs5F1H2gFNDWq1T2hoqW0Sp4Am8P43EOWfi9lP6+FbDArQrxpYKuZgwCc/nXcIH/AwuXZfLLHt/ZjGbx0zFqeBvEdJPM4/nlLd92xo1hv/cYI8eOUrQrhNdsDYCFN12cxY/G7LL3i3RzgWehj78KWNv61vkJXR5m80BngMOkhI6Rn+9OQMNbT0U/DySL7TO7nYMZTiOQPPp4z25PUxobCVlvBwY1uZx8vnF+E3DVrfTgf8aIilQxTlVaIfbbECu/Wer2cYDNAgMBAAECggEAPn4FdZ94133++LNoWdaKdDrcEQDGrozzvppmqG2xjLxo6h/NIMbR6s1JYj4yY4s4CeJv266EwRwdRfkyU+WJbaUdEwRAEbiLddyvL0paD3PdVf/cbxZZcycZjXEPCweE9762RxFa7nz2MdpVMLsMlN3CsQHt8NHWOg6LPqGw3c449LsToXb/ga1tiOS/2nVSKthAV1JNnkAZEWf8fegEgAwqydfBWv83N7r+Xc9lO5AMef31sLmQnuNE74Id9cRVH5TNp4MvJFXXyPq0bS+nDAfejuFoc0mqJ6u7xvjmLTyIx69JLJgYZyio73fcksCeWrKcUbHpJym+ARhhwrYDdQKBgQDCZtbc4UlCGJx81uhEeKI84pfDOMpKxAlRksWndpq+2MvNziUuVmXXfBCxrDd2NGM9mIyYvODyVUmLFGmd0MYqUnOaz49rsNiONpd01snmACtjzKMB2FF7G6qDgihOtqxeSInCSl1sJt5oR2kRbMcwEloS8FBWZH0nO6zsrwUA+wKBgQCxNNdQZsAl25s2K6WBfkQyriuS5Ve1gHcWs0/GNwgBfl8y/VJfVx6uk9+pXvOZYhdcExN+kjqrAjvZDBZVmItSDUIBQUnIa71PcG2yedQ9MgFMmIIOmt8WtI+IoJTjkhsc+iiMR2zMH2egPvIeHoUDioCPl++7fQBfV3iEFhWq1wKBgDCRKrrSGdBGf8n8ktiQXs/hOFMQfBGDumRDy9eTnQNy/C+1gbp64USdfTo2MUD5w5Ve6Dk8buJ8BjyV4/EGeIuYP8N8eXNJIkEdSGdrRdONVUnAlTTfyzN7bPUf7lwD7To82xXMKFzdtRDOTmSJDZZn71Lt8NQ0lMPZd9FFxHVDAoGAQmJAMt97JfOBzqZFJyCNHcs/iZUe6WCJvFhKD0A4YI7dzPU3MX4qgU3mIMXwTcqAY77Fs8nF7qA0mVe82i3+KyvKSTwTDuDFl4fPoGehSZd9AxuyxRPhdNkJWC6H+ESYoZ9ZJ0vuhv1Qzagm/X+DZtMw3BoX9c2bIRxcimbXkRsCgYEAgzUC50yGHZuFdYvggITryKMf4cX9tgej97oeOxa+eHVeOv6bvTtbZQ9MtQAKPO8Lo3rSOeFoEoN6OUS0XjxJ9tl9ImNknoBPiiOyv6CzTtDwdWWkhebaOjQtmWflrkqEMlJiSKw6//SVlDxFAsBHn7tyQiQ7P4wDSjXFEVrOT/g=";


    public static AlipayConfig getAlipayConfig() {
        AlipayConfig alipayConfig = new AlipayConfig();
        alipayConfig.setServerUrl("https://openapi.alipay.com/gateway.do");
        alipayConfig.setAppId(APPID);
        alipayConfig.setPrivateKey(PRIVATE_KEY);

        //设置应用公钥证书路径
        alipayConfig.setAppCertPath(AppParams.getInstance().crtsPathLinux + "/appCertPublicKey_2021005116652932.crt");
        //设置支付宝公钥证书路径
        alipayConfig.setAlipayPublicCertPath(AppParams.getInstance().crtsPathLinux + "/alipayCertPublicKey_RSA2.crt");
        //设置支付宝根证书路径
        alipayConfig.setRootCertPath(AppParams.getInstance().crtsPathLinux + "/alipayRootCert.crt");

        alipayConfig.setFormat("json");
        alipayConfig.setCharset("UTF-8");
        alipayConfig.setSignType("RSA2");

        return alipayConfig;
    }


    public static void directPayMerchantCreate() {

        try {

        } catch (Throwable e) {

        }
    }

    public static String directPayAppPay(JSONObject bean) {
        String orderStr = "";
        try {

            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            // 构造请求参数以调用接口
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();

            // 设置商户订单号
            model.setOutTradeNo(bean.getString("out_trade_no"));

            //      request.setNotifyUrl("http://47.121.179.98:8085/public/client/alipayCallback");

            //    model.setBody("{\"phone\":\"" + bean.getString("phone") + "\"}");
            // 设置订单总金额
            model.setTotalAmount(bean.getString("total_amount"));

            // 设置订单标题
            model.setSubject(bean.getString("subject"));

            // 设置产品码
            model.setProductCode("QUICK_MSECURITY_PAY");

            // 设置二级商户信息
            SubMerchant subMerchant = new SubMerchant();
            subMerchant.setMerchantId(bean.getString("merchant_id"));
            model.setSubMerchant(subMerchant);

            // 设置结算信息
            SettleInfo settleInfo = new SettleInfo();
            List<SettleDetailInfo> settleDetailInfos = new ArrayList<>();

            SettleDetailInfo settleDetailInfo = new SettleDetailInfo();
            settleDetailInfo.setAmount(bean.getString("total_amount"));
            settleDetailInfo.setTransInType("defaultSettle");
            settleDetailInfos.add(settleDetailInfo);

            settleInfo.setSettleDetailInfos(settleDetailInfos);
            model.setSettleInfo(settleInfo);

            request.setBizModel(model);

            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            orderStr = response.getBody();

            if (response.isSuccess()) {
                System.out.println("调用成功");
            }
            else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
            }
        } catch (Throwable e) {

            throw new RuntimeException(e);
        }
        return orderStr;
    }

    public static boolean directPayAppPayQuery(JSONObject bean) {
        try {

            AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());

            // 构造请求参数以调用接口
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();

            // 设置订单支付时传入的商户订单号
            model.setOutTradeNo(bean.getString("out_trade_no"));


            // 设置查询选项
            List<String> queryOptions = new ArrayList<String>();
            queryOptions.add("trade_settle_info");
            model.setQueryOptions(queryOptions);

            request.setBizModel(model);
            // 第三方代调用模式下请设置app_auth_token
            // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");

            AlipayTradeQueryResponse response = alipayClient.certificateExecute(request);
            System.out.println(response.getBody());

            if (response.isSuccess()) {
                System.out.println("query 调用成功");
                // alipay_trade_query_response  trade_status  TRADE_SUCCESS TRADE_CLOSED WAIT_BUYER_PAY TRADE_FINISHED

                try {
                    JSONObject responseJ = JSONObject.parseObject(response.getBody());
                    responseJ = JSONObject.parseObject(responseJ.getString("alipay_trade_query_response"));

                    if (Objects.equals(responseJ.getString("trade_status"), "WAIT_BUYER_PAY")) {

                        System.out.println("1");
                        return false;
                    }
                    else if (Objects.equals(responseJ.getString("trade_status"), "TRADE_FINISHED")) {
                        System.out.println("2");
                        return false;
                    }
                    else if (Objects.equals(responseJ.getString("trade_status"), "TRADE_CLOSED")) {
                        System.out.println("3");

                        return false;
                    }
                    else if (Objects.equals(responseJ.getString("trade_status"), "TRADE_SUCCESS")
                            && Objects.equals(responseJ.getString("out_trade_no"), bean.getString("out_trade_no"))
                            && bean.getDoubleValue("total_amount") == Double.parseDouble(responseJ.getString("total_amount"))) {

                        bean.put("total_amount", Double.parseDouble(responseJ.getString("receipt_amount")));
                        return true;
                    }

                } catch (Throwable e) {
                    System.out.println("4");
                    return false;
                }
                System.out.println("5");

                return false;

            }
            else {
                System.out.println("调用失败");
                // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
                // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
                // System.out.println(diagnosisUrl);
                System.out.println("6");

                return false;
            }
        } catch (Throwable e) {
            return false;
        }
    }

}
